package com.example.demo.zaqizabatest.多线程相关;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ABC
 * @Author lys4134
 * @Date 2021/09/01 17:41:14
 * @Description ABC
 * @Version 1.0
 **/
@SuppressWarnings({"AlibabaLockShouldWithTryFinally", "AlibabaAvoidManuallyCreateThread"})
public class ABC2 {
    private static Lock lock = new ReentrantLock();
    //Lock lock=new ReentrantLock(true);//公平锁
    //Lock lock=new ReentrantLock(false);//非公平锁
    private static Condition condition = lock.newCondition();//创建 Condition
    private static volatile int i = 0;

    public static void main(String[] args) {

        new Thread(() -> printA()).start();
        new Thread(() -> printB()).start();
        new Thread(() -> printC()).start();
    }


    @SneakyThrows
    private static void printA() {
        while (true) {
            lock.lock();
            if (i % 3 == 0) {
                System.out.print("A");
                i++;
                condition.signalAll();
            } else {
                condition.await();
            }
        }
    }

    @SneakyThrows
    private static void printB() {
        while (true) {
            lock.lock();
            if (i % 3 == 1) {
                System.out.print("B");
                i++;
                condition.signalAll();
            } else {
                condition.await();
            }
        }
    }

    @SneakyThrows
    private static void printC() {
        while (true) {
            lock.lock();
            if (i % 3 == 2) {
                System.out.print("C");
                i++;
                condition.signalAll();
            } else {
                condition.await();
            }
        }
    }
}
